package com.scuec.trainingmanagementsys.service.impl;

import com.scuec.trainingmanagementsys.entity.Grade;
import com.scuec.trainingmanagementsys.mapper.GradeMapper;
import com.scuec.trainingmanagementsys.service.GradeService;
import com.scuec.trainingmanagementsys.service.TeamMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GradeServiceImpl implements GradeService {
    @Autowired
    private GradeMapper gradeMapper;

    @Autowired
    private TeamMemberService teamMemberService;

    @Override
    public int saveGrade(Grade grade) {
        // 检查是否已存在该小组的评分
        Grade existingGrade = getGradeByProjectAndTeam(grade.getProjectId(), grade.getTeamId());
        if (existingGrade != null) {
            // 存在则更新
            grade.setGradeId(existingGrade.getGradeId());
            return gradeMapper.updateGrade(grade);
        } else {
            // 不存在则插入
            return gradeMapper.insertGrade(grade);
        }
    }

    @Override
    public Grade getGradeByProjectAndTeam(Integer projectId, Integer teamId) {
        return gradeMapper.getGradeByProjectAndTeam(projectId, teamId);
    }

    @Override
    public List<Grade> getGradesByProjectId(Integer projectId) {
        return gradeMapper.getGradesByProjectId(projectId);
    }

    @Override
    public int updateGrade(Grade grade) {
        // 若gradeId为空，通过项目和小组ID查找
        if (grade.getGradeId() == null) {
            Grade existing = getGradeByProjectAndTeam(grade.getProjectId(), grade.getTeamId());
            if (existing != null) {
                grade.setGradeId(existing.getGradeId());
            } else {
                return 0; // 无记录，更新失败
            }
        }
        return gradeMapper.updateGrade(grade);
    }

    @Override
    public Grade getGradeByProjectAndStudent(Integer projectId, Integer studentId) {
        // 通过学生ID获取团队ID
        Integer teamId = teamMemberService.getTeamIdByStudentId(studentId);
        if (teamId != null) {
            return gradeMapper.getGradeByProjectAndTeam(projectId, teamId);
        }
        return null;
    }
}